package com.spzx.product.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.spzx.product.domain.Category;
import com.spzx.product.enums.DelFlagStatus;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.vo.CategoryExcelVo;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;

public class CategoryExcelListener extends AnalysisEventListener<CategoryExcelVo> {

    private Map<String, Category> dataCache = new HashMap<>();

    private Set<Long> categoryIds;

    private CategoryMapper categoryMapper;

    public CategoryExcelListener(CategoryMapper categoryMapper) {
        this.categoryIds = categoryMapper.selectIds();
        this.categoryMapper = categoryMapper;
    }

    /**
     * 每解析一行数据就会调用一次该方法
     *
     * @param excelVo
     * @param analysisContext
     */
    @Override
    public void invoke(CategoryExcelVo excelVo, AnalysisContext analysisContext) {
        if (!categoryIds.contains(excelVo.getId())) {
            String key = excelVo.getName() + "-" + excelVo.getParentId();
            Category category = new Category();
            category.setDelFlag(DelFlagStatus.OK.getCode());
            BeanUtils.copyProperties(excelVo, category);
            dataCache.put(key, category);
        }
    }

    /**
     * excel解析完毕以后需要执行的代码
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<Category> categoryList = dataCache.values().stream().toList();
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryMapper.saveBatch(categoryList);
        }
    }
}
